import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Spin, Button, Breadcrumb, Table } from 'antd';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import styles from './index.less'
import china from '@/assets/china.json'
import * as echarts from 'echarts';
import { EChartsType } from 'echarts/core';
import classnames from 'classnames';
import { RightOutlined } from '@ant-design/icons';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';


const provinceList = [
  {
    name: '北京市',
    nameKey: '北京',
    adcode: 110000,
  },
  {
    name: '天津市',
    nameKey: '天津',
    adcode: 120000,
  },
  {
    name: '河北省',
    nameKey: '河北',
    adcode: 130000,
  },
  {
    name: '山西省',
    nameKey: '山西',
    adcode: 140000,
  },
  {
    name: '内蒙古自治区',
    nameKey: '内蒙',
    adcode: 150000,
  },
  {
    name: '辽宁省',
    nameKey: '辽宁',
    adcode: 210000,
  },
  {
    name: '吉林省',
    nameKey: '吉林',
    adcode: 220000,
  },
  {
    name: '黑龙江省',
    nameKey: '黑龙江',
    adcode: 230000,
  },
  {
    name: '上海市',
    nameKey: '上海',
    adcode: 310000,
  },
  {
    name: '江苏省',
    nameKey: '江苏',
    adcode: 320000,
  },
  {
    name: '浙江省',
    nameKey: '浙江',
    adcode: 330000,
  },
  {
    name: '安徽省',
    nameKey: '安徽',
    adcode: 340000,
  },
  {
    name: '福建省',
    nameKey: '福建',
    adcode: 350000,
  },
  {
    name: '江西省',
    nameKey: '江西',
    adcode: 360000,
  },
  {
    name: '山东省',
    nameKey: '山东',
    adcode: 370000,
  },
  {
    name: '河南省',
    nameKey: '河南',
    adcode: 410000,
  },
  {
    name: '湖北省',
    nameKey: '湖北',
    adcode: 420000,
  },
  {
    name: '湖南省',
    nameKey: '湖南',
    adcode: 430000,
  },
  {
    name: '广东省',
    nameKey: '广东',
    adcode: 440000,
  },
  {
    name: '广西壮族自治区',
    nameKey: '广西',
    adcode: 450000,
  },
  {
    name: '海南省',
    nameKey: '海南',
    adcode: 460000,
  },
  {
    name: '重庆市',
    nameKey: '重庆',
    adcode: 500000,
  },
  {
    name: '四川省',
    nameKey: '四川',
    adcode: 510000,
  },
  {
    name: '贵州省',
    nameKey: '贵州',
    adcode: 520000,
  },
  {
    name: '云南省',
    nameKey: '云南',
    adcode: 530000,
  },
  {
    name: '西藏自治区',
    nameKey: '西藏',
    adcode: 540000,
  },
  {
    name: '陕西省',
    nameKey: '陕西',
    adcode: 610000,
  },
  {
    name: '甘肃省',
    nameKey: '甘肃',
    adcode: 620000,
  },
  {
    name: '青海省',
    nameKey: '青海',
    adcode: 630000,
  },
  {
    name: '宁夏回族自治区',
    nameKey: '宁夏',
    adcode: 640000,
  },
  {
    name: '新疆维吾尔自治区',
    nameKey: '新疆',
    adcode: 650000,
  },
  {
    name: '台湾省',
    nameKey: '台湾',
    adcode: 710000,
  },
  {
    name: '香港特别行政区',
    nameKey: '香港',
    adcode: 810000,
  },
  {
    name: '澳门特别行政区',
    nameKey: '澳门',
    adcode: 820000,
  },
]
const levelData = {
  0: '低风险',
  1: '中风险',
  2: '高风险',
}

const mapStateToProps = (state: any) => ({
  platformOverview: state.platformOverview,
  loading: state.loading.models["platformOverview"],
})
class Overview extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any
  };
  constructor(props: any) {
    super(props);
    this.state = {
      mapEchart: null as EChartsType,
      annularChart1: null as EChartsType,
      annularChart2: null as EChartsType,
      annularChart3: null as EChartsType,
      annularChart4: null as EChartsType,
      lineChart1: null as EChartsType,
      lineChart2: null as EChartsType,
      carsData: [],
      provinceData: [],
      // overviewData: {}, 
      brandList: [],  //  品牌
      brandIdx: 0,
      currentBrand: '',
      currentCode: '',  //  当前品牌
      currentData: {},  //  基本信息
      typeConfig: [], //  预警类型
      levelConfig: [
        {
          value: 2,
          label: '高风险',
        },
        {
          value: 1,
          label: '中风险',
        },
        {
          value: 0,
          label: '低风险',
        },
      ],  //  预警级别
      annularChart1Data: [], //  累计电池故障预警类型占比
      annularChart2Data: [],  //  累计电池故障预警级别占比
      annularChart3Data: [],  //  电池故障预警类型占比
      annularChart4Data: [],  //  电池故障预警级别占比
      lineChart1Data: [], //  电池故障预警类型数量趋势
      lineChart2Data: [], //  电池故障预警级别数量对比
      xAxisLineChart1: [],
      xAxisLineChart2: [],
      annularChart3DateType: 1,
      annularChart4DateType: 1,
      lineChart1DateType: 1,
      lineChart2DateType: 1,
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const mapEchart = echarts.init(document.getElementById('mapEchart') as HTMLElement);
    const annularChart1 = echarts.init(document.getElementById('annularChart1') as HTMLElement);
    const annularChart2 = echarts.init(document.getElementById('annularChart2') as HTMLElement);
    const annularChart3 = echarts.init(document.getElementById('annularChart3') as HTMLElement);
    const annularChart4 = echarts.init(document.getElementById('annularChart4') as HTMLElement);
    const lineChart1 = echarts.init(document.getElementById('lineChart1') as HTMLElement);
    const lineChart2 = echarts.init(document.getElementById('lineChart2') as HTMLElement);
    this.setState({
      mapEchart: mapEchart,
      annularChart1: annularChart1,
      annularChart2: annularChart2,
      annularChart3: annularChart3,
      annularChart4: annularChart4,
      lineChart1: lineChart1,
      lineChart2: lineChart2,
    })
    echarts.registerMap('china', china, {});
    // const mapOption = this.getMapOption('china');
    // mapEchart.setOption(mapOption);
    
    //  刷新页面会重新获取info信息，此时可能拿不到 dicData 数据
    if (sessionStorage.getItem('warningTypeConfig')) {
      const typeData: any = sessionStorage.getItem('warningTypeConfig')
      this.setState({
        typeConfig:  JSON.parse(typeData) || [],
      })
    } else {
      const typeData = getDictOptionsByCode(this.context.dicData, 'faultType')
      sessionStorage.setItem('warningTypeConfig', JSON.stringify(typeData))
      this.setState({
        typeConfig:  typeData || [],
      })
    }

    //  获取品牌数据
    this.getBrandData();
    const _this = this
    window.onresize = function() {
      _this.state.mapEchart.resize();
      _this.state.annularChart1.resize();
      _this.state.annularChart2.resize();
      _this.state.annularChart3.resize();
      _this.state.annularChart4.resize();
      _this.state.lineChart1.resize();
      _this.state.lineChart2.resize();
    };
  }

  getMapOption = (mapName: string) => {
    return {
      geo: {
        selectedMode: false,
        id: 'myMap',
        emphasis: {
          itemStyle: {
            shadowColor: 'rgba(0,0,0,0.06)',
            shadowBlur: 10,
            shadowOffsetX: 5,
            shadowOffsetY: 5,
            borderWidth: 0,
            areaColor: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: '#3885F2', // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#45B2F9', // 100% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          },
          label: {
            height: 50,
            borderRadius: 10,
            shadowColor: 'rgba(0,0,0,0.06)',
            shadowBlur: 10,
            shadowOffsetX: 5,
            shadowOffsetY: 5,
            position: ['40%', 100],
            formatter: params => {
              let count = this.getProvinceCount(params.name)
              return (
                '{a|}{b|' +
                params.name +
                '}' +
                '\n{c|电池故障预警：' +
                count +
                '}'
                /* '}\n{d|离线：' +
                offlineCarsNumber +
                '}' */
              );
            },
            padding: [10, 10, 0, 10],
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            rich: {
              a: {
                width: 6,
                height: 6,
                borderRadius: 3,
                backgroundColor: '#0072FE',
                align: 'left',
              },
              b: {
                align: 'left',
                padding: [0, 0, 0, 5],
                color: 'black',
              },
              c: {
                color: '#0070FC',
                fontSize: 12,
                align: 'left',
                padding: [10, 0, 0, 0],
              },
              /* d: {
                color: '#0070FC',
                fontSize: 12,
                align: 'left',
                padding: [5, 0, 0, 0],
              }, */
            },
          },
        },
        map: mapName,
        roam: false,
        itemStyle: {
          areaColor: '#E0F1FE',
          borderColor: '#E0F1FE',
        },
      },
    };
  };

  //  获取品牌数据列表
  getBrandData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'platformOverview/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            currentCode: res.data[0]?.brandCode || '',
            currentBrand: res.data[0]?.brandName || '',
            brandList: res.data || []
          })
          this.getOverviewData(res.data[0]?.brandCode)
        }
      }
    })
  }

  changeBrand = () => {
    const { brandList, brandIdx } = this.state
    if (brandList && brandList.length <= 1) return;
    this.setState({
      brandIdx: brandIdx + 1
    }, () => {
      let idx = (brandIdx + 1)%brandList.length
      let brand = {
        name: brandList[idx].brandName,
        code: brandList[idx].brandCode
      }
      this.setState({
        currentBrand: brand.name,
        currentCode: brand.code,
      })
      this.getOverviewData(brand.code)
    })
  }

  //  获取品牌预警信息总览
  getOverviewData = async (brandCode: any, params = {}) => {
    const { dispatch } = this.props
    brandCode && dispatch({
      type: 'platformOverview/getDataWithRes',
      payload: {
        url: '/battery/monitor/data/search',
        brandCode,
        ...params
      },
      callback: (res: any) => {
        const { mapEchart, annularChart1, annularChart2, annularChart3, annularChart4, lineChart1, lineChart2 } = this.state;
        if (res.statusCode === '0') {
          const platData = this.formatPlatFormData(res.data)  //  平台数据

          this.setState({
            annularChart3DateType: 1,
            annularChart4DateType:  1,
            lineChart1DateType: 1,
            lineChart2DateType: 1,
            currentData: platData,
            provinceData: res.data.warningByProvinceList || [],
          }, () => {
            const mapOption = this.getMapOption('china');
            mapEchart.setOption(mapOption);

            //  设置chart1数据
            const tempAnnular1Data = this.formatAnnular1Data(res.data.warningByTypeList);
            this.setState({
              annularChart1Data: tempAnnular1Data
            }, () => {
              const tempAnnular1Option = this.formatAnnularTypeOption(tempAnnular1Data);
              if (!annularChart1) {
                const annularChart1 = echarts.init(document.getElementById('annularChart1') as HTMLElement)
                this.setState({
                  annularChart1: annularChart1
                })
              }
              annularChart1.setOption(tempAnnular1Option)
            })

            //  设置chart2数据
            const tempAnnular2Data = this.formatAnnular2Data(res.data.warningByLevelList);
            this.setState({
              annularChart2Data: tempAnnular2Data
            }, () => {
              const tempAnnular2Option = this.formatAnnularLevelOption(tempAnnular2Data)
              if (!annularChart2) {
                const annularChart2 = echarts.init(document.getElementById('annularChart2') as HTMLElement)
                this.setState({
                  annularChart2: annularChart2
                })
              }
              annularChart2.setOption(tempAnnular2Option)
            })

            //  设置chart3数据
            const tempAnnular3Data = this.formatAnnular3Data(res.data.warningByTypeList);
            this.setState({
              annularChart3Data: tempAnnular3Data
            }, () => {
              const tempAnnular3Option = this.formatAnnularTypeOption(tempAnnular3Data)
              if (!annularChart3) {
                const annularChart3 = echarts.init(document.getElementById('annularChart3') as HTMLElement)
                this.setState({
                  annularChart3: annularChart3
                })
              }
              annularChart3.setOption(tempAnnular3Option)
            })

            //  设置chart4数据
            const tempAnnular4Data = this.formatAnnular4Data(res.data.warningByLevelList);
            this.setState({
              annularChart4Data: tempAnnular4Data
            }, () => {
              const tempAnnular4Option = this.formatAnnularLevelOption(tempAnnular4Data)
              if (!annularChart4) {
                const annularChart4 = echarts.init(document.getElementById('annularChart4') as HTMLElement)
                this.setState({
                  annularChart4: annularChart4
                })
              }
              annularChart4.setOption(tempAnnular4Option)
            })

            const daysList = this.createDaysList(7)
            this.setState({
              xAxisLineChart1: daysList,
              xAxisLineChart2: daysList
            }, () => {
              //  设置chart5数据
              const tempLine1Data: any = this.formatLine1Data(res.data.warningByTypeList);
              const tempLine1Option = this.formatLine1Option(tempLine1Data);
              if (!lineChart1) {
                const lineChart1 = echarts.init(document.getElementById('lineChart1') as HTMLElement);
                this.setState({
                  lineChart1: lineChart1
                })
              }
              lineChart1.setOption(tempLine1Option);

              //  设置chart6数据
              const tempLine2Data = this.formatLine2Data(res.data.warningByLevelList);
              const tempLine2Option = this.formatLine2Option(tempLine2Data);
              if (!lineChart2) {
                const lineChart2 = echarts.init(document.getElementById('lineChart2') as HTMLElement);
                this.setState({
                  lineChart2: lineChart2
                })
              }
              lineChart2.setOption(tempLine2Option);

            })
          })
        }
      }
    })
  }


  //  totalCount 平台接入车辆数, newCount 今日新接入车辆数, warningCount 累计预警车辆数, highWarningCount 累计高风险预警车辆数  
  formatPlatFormData = (data: any) => {
    const { updateTime, warningByLevelList, vehicleData: { totalCount, newCount, warningCount, highWarningCount } } = data
    const res = {
      totalCount, //  平台接入车辆数
      newCount, //  今日新接入车辆数
      warningCount, //  累计预警车辆数
      highWarningCount, //  累计高风险预警车辆数
      faultNum: 0,  //  电池故障预警数
      levelHighNum: 0,  //  高风险预警数
      faultNumTotal: 0, //  累计电池故障预警数
      levelHighNumTotal: 0,  //  累计高风险预警数
      levelHighHandlingNum: 0, // 高风险预警处理中
      levelHighHandledNum: 0, //  高风险预警处理完成
      updateTime
    }

    warningByLevelList && warningByLevelList.forEach((item: any) => {
      res.faultNum += item.currentCount
      res.faultNumTotal += item.totalCount
      if (item.warningLevel == 2) {
        res.levelHighNum = item.currentCount
        res.levelHighNumTotal = item.totalCount
        res.levelHighHandlingNum = item.handlingCount
        res.levelHighHandledNum = item.handledCount
      }
    })
    return res
  }

  changeDate = (type: number, date: number, chartId: string) => {
    const { dispatch } = this.props
    const { currentCode, annularChart3, annularChart4, lineChart1, lineChart2 } = this.state
    const daysConfig = {
      1: 7,
      2: 30,
    }
    const tempDay = daysConfig[date];
    const daysList = this.createDaysList(tempDay);
    dispatch({
      type: 'platformOverview/getDataWithRes',
      payload: {
        url: '/battery/monitor/data/search',
        brandCode: currentCode,
        type,
        date
      },
      callback: (res: any) => {
        if (res.statusCode == 0) {
          // warningByTypeList
          if (type == 0) {
            //  预警类型
            if (chartId === 'annularChart3') {
              const tempAnnular3Data = this.formatAnnular3Data(res.data.warningByTypeList)
              const tempAnnular3Option = this.formatAnnularTypeOption(tempAnnular3Data)
              annularChart3.setOption(tempAnnular3Option)
              // annularChart3.clear()
            }
            if (chartId === 'lineChart1') {
              this.setState({
                xAxisLineChart1: daysList
              }, () => {
                const tempLine1Data: any = this.formatLine1Data(res.data.warningByTypeList)
                const tempLine1Option = this.formatLine1Option(tempLine1Data)
                lineChart1.setOption(tempLine1Option)
              })
              // lineChart1.clear()
              return;
            }
            
          }
          if (type == 1) {
            //  预警级别
            if (chartId === 'annularChart4') {
              const tempAnnular4Data = this.formatAnnular4Data(res.data.warningByLevelList)
              const tempAnnular4Option = this.formatAnnularTypeOption(tempAnnular4Data)
              annularChart4.setOption(tempAnnular4Option)
              // annularChart4.clear()
              return;
            }
            if (chartId === 'lineChart2') {
              this.setState({
                xAxisLineChart2: daysList
              }, () => {
                const tempLine2Data = this.formatLine2Data(res.data.warningByLevelList)
                const tempLine2Option = this.formatLine2Option(tempLine2Data)
                lineChart2.setOption(tempLine2Option)
              })
              // lineChart2.clear()
              return;
            }
            
          }
        }
      }
    })
  }

  //  近7、30天
  createDaysList = (num: number) => {
    let ds = [...new Array(num)].map((i, idx) => moment().startOf("day").subtract(idx, "days").format("YYYY-MM-DD"));
    ds.reverse();
    return ds;
  }

  //  整理预警类型Option（饼图）
  formatAnnularTypeOption = (data: any) => {
    return {
      legend: {
        selectedMode: false,
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        itemGap: 15,
        top: 'middle',
        icon: 'circle',
        itemHeight: 8,
        textStyle: {
          rich: {
            a: {
              width: 50,
              fontSize: 10,
            },
            b: {
              width: 50,
              align: 'right',
              color: 'rgba(0, 0, 0, 0.5)',
              fontSize: 10,
            },
            c: {
              width: 50,
              align: 'right',
              color: 'rgba(0, 0, 0, 0.5)',
              fontSize: 10,
            },
          },
        },
        formatter: (name: string) => {
          let value = 0;
          data.map(item => (item.name === name ? (value = item.count) : 0));
          let totalValue = 0;
          data.map(item => (totalValue += item.count));
          let percent = ((value * 100) / totalValue).toFixed(2);
          percent = isNaN(percent) ? '--' : percent;
          return `{a|${name}}{b|${value}}{c|${percent}%}`;
        },
      },
      series: [
        {
          silent: true,
          name: '累计电池故障预警类型占比',
          type: 'pie',
          radius: ['20%', '40%'],
          center: ['25%', '50%'],
          avoidLabelOverlap: false,
          clockwise: false,
          label: {
            show: false,
            position: 'center',
          },
          labelLine: {
            show: false,
          },
          data: data.map(item => {
            return {
              name: item.name,
              value: item.count,
            };
          }),
        },
      ],
    }
  }

  //  整理预警级别Option（饼图）
  formatAnnularLevelOption = (data: any) => {
    return {
      legend: {
        selectedMode: false,
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        itemGap: 15,
        top: 'middle',
        icon: 'circle',
        itemHeight: 8,
        textStyle: {
          rich: {
            a: {
              width: 50,
              fontSize: 10,
              padding: [0,0,0,0],
            },
            b: {
              width: 50,
              align: 'right',
              color: 'rgba(0, 0, 0, 0.5)',
              fontSize: 10,
              padding: [0,0,0,0],
            },
            c: {
              width: 50,
              align: 'right',
              color: 'rgba(0, 0, 0, 0.5)',
              fontSize: 10,
            },
          },
        },
        formatter: (name: string) => {
          let value = 0;
          data.map(item => (item.name === name ? (value = item.count) : 0));
          let totalValue = 0;
          data.map(item => (totalValue += item.count));
          let percent = ((value * 100) / totalValue).toFixed(2);
          percent = isNaN(percent) ? '--' : percent;
          return `{a|${name}}{b|${value}}{c|${percent}%}`;
        },
      },
      series: [
        {
          silent: true,
          name: '累计电池故障预警等级占比',
          type: 'pie',
          radius: ['20%', '40%'],
          center: ['25%', '50%'],
          avoidLabelOverlap: false,
          clockwise: false,
          label: {
            show: false,
            position: 'center',
          },
          labelLine: {
            show: false,
          },
          data: data.map(item => {
            return {
              name: item.name,
              value: item.count,
            };
          }),
        },
      ],
    }
  }

  //  整理预警类型Option（折线图）
  formatLine1Option = (data: any) => {
    const { xAxisLineChart1 } = this.state
    let legendList: string[] = []
    let dataList: any[] = []
    data.forEach((item: any) => {
      legendList.push(item.label)
      dataList.push(item.list)
    })
    return {
      grid: {
        top: '10%',
        left: '5%',
        right: '5%',
        bottom: '10%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        borderWidth: 1,
        axisPointer: {
          type: 'shadow'
        },
        extraCssText: 'z-index:2'
      },
      legend: [{
        top: '8px',
        right: '0%',
        orient: 'horizontal',
        data: legendList,
        itemWidth: 0,
        itemHeight: 0,
        itemGap: 0,
        // borderRadius: 4,
        icon: 'none',
        textStyle: {
          color: '#228CFF',
          // fontFamily: 'Alibaba PuHuiTi',
          fontSize: 10,
          fontWeight: 400
        }
      }],
      xAxis: {
        type: 'category',
        data: xAxisLineChart1,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#393939' //X轴文字颜色
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '',
          minInterval: 1,
          nameTextStyle: {
            color: '#000',
            // fontFamily: 'Alibaba PuHuiTi',
            fontSize: 14,
            fontWeight: 600
            // padding: [0, 0, 0, 40], // 四个数字分别为上右下左与原位置距离
          },
          nameGap: 30,  // 表现为上下位置
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#393939',
            fontSize: 14
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          }
        }
      ],
      series: dataList.map((item: any, idx: number) => {
        return {
          name: legendList[idx],
          type: 'line',
          showAllSymbol: true, // 显示所有图形。
          //  标记的图形为实心圆
          symbolSize: 0, //标记的大小
          /* itemStyle: {
            //折线拐点标志的样式
            color: 'white',
            borderWidth: '2',
            borderColor: '#5470c6',
            normal: {
              color: '#5470c6'//拐点颜色
            }
          }, */
          /* lineStyle: {
            color: '#5470c6'
          }, */
          data: item
        }
      })
    }
  }

  //  整理预警级别Option（折线图）
  formatLine2Option = (data: any) => {
    const { xAxisLineChart2 } = this.state
    let legendList: string[] = []
    let dataList: any[] = []
    data.forEach((item: any) => {
      legendList.push(item.label)
      dataList.push(item.list)
    })
    return {
      grid: {
        top: '10%',
        left: '5%',
        right: '5%',
        bottom: '10%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        borderWidth: 1,
        axisPointer: {
          type: 'shadow'
        },
        extraCssText: 'z-index:2'

      },
      legend: [{
        top: '8px',
        right: '0%',
        orient: 'horizontal',
        data: legendList,
        itemWidth: 0,
        itemHeight: 0,
        itemGap: 0,
        // borderRadius: 4,
        icon: 'none',
        textStyle: {
          color: '#228CFF',
          // fontFamily: 'Alibaba PuHuiTi',
          fontSize: 10,
          fontWeight: 400
        }
      }],
      xAxis: {
        type: 'category',
        data: xAxisLineChart2,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#393939' //X轴文字颜色
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '',
          minInterval: 1,
          nameTextStyle: {
            color: '#000',
            // fontFamily: 'Alibaba PuHuiTi',
            fontSize: 14,
            fontWeight: 600
            // padding: [0, 0, 0, 40], // 四个数字分别为上右下左与原位置距离
          },
          nameGap: 30,  // 表现为上下位置
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#393939',
            fontSize: 14
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          }
        }
      ],
      series: dataList.map((item: any, idx: number) => {
        return {
          name: legendList[idx],
          type: 'line',
          showAllSymbol: true, // 显示所有图形
          symbolSize: 0, // 标记的大小
          data: item
        }
      })
    }
  }

  //  整理chart1数据
  formatAnnular1Data = (list: Array<any>) => {
    if (!list) return [];
    const { typeConfig } = this.state
    return typeConfig.map(t => {
      let tempData = {
        type: t.value,
        name: t.label,
        count: 0
      }
      list.some(item => {
        const status = item.warningType == t.value;
        if (status) {
          tempData.count = item.totalCount
        }
        return status
      })
      return tempData
    })
  }

  //  整理chart2数据
  formatAnnular2Data = (list: Array<any>) => {
    if (!list) return [];
    return [2, 1, 0].map(i => {
      let tempData = {
        type: i,
        name: levelData[i],
        count: 0
      }
      list.some(item => {
        const status = item.warningLevel == i;
        if (status) {
          tempData.count = item.totalCount
        }
        return status
      })
      return tempData;
    })
  }

  //  整理chart3数据
  formatAnnular3Data = (list: Array<any>) => {
    if (!list) return [];
    const { typeConfig } = this.state
    return typeConfig.map(t => {
      let tempData = {
        type: t.value,
        name: t.label,
        count: 0
      }
      list.some(item => {
        const status = item.warningType == t.value;
        if (status) {
          tempData.count = item.detailCount
        }
        return status
      })
      return tempData
    })
  }

  //  整理chart4数据
  formatAnnular4Data = (list: Array<any>) => {
    if (!list) return [];
    return [2, 1, 0].map(i => {
      let tempData = {
        type: i,
        name: levelData[i],
        count: 0
      }
      list.some(item => {
        const status = item.warningLevel == i;
        if (status) {
          tempData.count = item.detailCount
        }
        return status
      })
      return tempData;
    })
  }

  //  整理chart5数据
  formatLine1Data = (list: Array<any>) => {
    // if (!list) return [];
    const { xAxisLineChart1 } = this.state;
    const { typeConfig } = this.state;
    const totalData = {};
    list && list.forEach(item => {
      //  7/30天
      totalData[item.warningType] = xAxisLineChart1.map(x => {
        let num = 0
        
        item.detailList.some(d => {
          const status = d.day.indexOf(x) !== -1;
          if (status) {
            num = d.count
          }
          return status
        })
        return num
      })
    })
    const arrayLen = xAxisLineChart1.length;
    const tempArr = this.createNumArray(arrayLen);

    return typeConfig.map(item => {
      let tempData = totalData[item.value] || tempArr;
      return {
        ...item,
        list: tempData
      }
    })
  }

  formatLine2Data = (list: Array<any>) => {
    const { xAxisLineChart2 } = this.state;
    const { levelConfig } = this.state;
    const totalData = {}
    list && list.forEach(item => {
      //  7/30天
      totalData[item.warningLevel] = xAxisLineChart2.map(x => {
        let num = 0
        item.detailList.some(d => {
          const status = d.day.indexOf(x) !== -1;
          if (status) {
            num = d.count
          }
          return status
        })
        return num
      })
    })
    const arrayLen = xAxisLineChart2.length;
    const tempArr = this.createNumArray(arrayLen);

    return levelConfig.map(item => {
      let tempData = totalData[item.value] || tempArr;
      return {
        ...item,
        list: tempData
      }
    })
  }

  createNumArray = (len: number) => {
    return new Array(len).fill(0)
  }

  changeLineChart1Date = (date: number) => {
    const chartId = 'lineChart1'
    const { lineChart1DateType } = this.state
    if (lineChart1DateType == date) return;
    this.setState({
      lineChart1DateType: date
    }, () => {
      this.changeDate(0, date, chartId)
    })
  }

  changeLineChart2Date = (date: number) => {
    const chartId = 'lineChart2'
    const { lineChart2DateType } = this.state
    if (lineChart2DateType == date) return;
    this.setState({
      lineChart2DateType: date
    }, () => {
      this.changeDate(1, date, chartId)
    })
  }

  changeAnnularChart3Date = (date: number) => {
    const chartId = 'annularChart3'
    const { annularChart3DateType } = this.state
    if ( annularChart3DateType == date ) return;
    this.setState({
      annularChart3DateType: date
    }, () => {
      this.changeDate(0, date, chartId)
    })
  }

  changeAnnularChart4Date = (date: number) => {
    const chartId = 'annularChart4'
    const { annularChart4DateType } = this.state
    if ( annularChart4DateType == date ) return;
    this.setState({
      annularChart4DateType: date
    }, () => {
      this.changeDate(1, date, chartId)
    })
  }

  //  获取省份名
  getProvinceName = (name: string) => {
    let provinceName = ''
    provinceList.some(p => {
      const status = name.indexOf(p.nameKey) !== -1
      if (status) {
        provinceName = p.name
      }
      return status
    })
    return provinceName
  }

  //  获取省份数据
  getProvinceCount = (name: string) => {
    const { provinceData } = this.state
    let provinceKey = ''
    provinceList.some(p => {
      const status = name.indexOf(p.name) !== -1
      if (status) {
        provinceKey = p.nameKey
      }
      return status
    })
    let count = 0
    provinceKey && provinceData.some((item: any) => {
      const status = item.province.indexOf(provinceKey) !== -1
      if (status) {
        count = item.totalCount
      }
      return status
    })
    return count
  }

  //  跳转电池故障预警
  goPageFaultWarning = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/newEnergyBatteryMonitor/batteryFaultWarning' }));
  }

  //  跳转预警车辆管理
  goPageWarningVehicle = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/newEnergyBatteryMonitor/warningVehicle' }));
  }

  render() {
    const { loading } = this.props
    const { currentBrand, currentData, provinceData, annularChart3DateType, annularChart4DateType, lineChart1DateType, lineChart2DateType } = this.state;
    const columns = [
      {
        title: '排名',
        dataIndex: 'index',
        width: 40,
        render: (text: any, record: any, index: any) => {
          return index + 1;
        },
      }, {
        title: '地区',
        dataIndex: 'province',
        width: 110,
      }, {
        title: '电池故障预警次数',
        dataIndex: 'totalCount',
        width: 120,
      }
    ]

    const dataSource = provinceData.sort((a, b) => {
      return b.totalCount - a.totalCount
    })

    return (
      <div className={styles.root}>
        <Card bordered={false}>
          <div className={styles.topView}>
            <div className={styles.topViewLeft}>
            {/* {classnames('','')} */}
            {/* {classnames(styles.corner, {[styles.activeCorner]: 1 === 'brand'})} */}
              <div className={styles.view1}>
                <div className={styles.brandPanel}>
                  <div className={styles.brandList}>{currentBrand}</div>
                  <RightOutlined className={styles.iconRightLine} onClick={() => {
                    this.changeBrand()
                  }} style={{
                    color: '#228cff',
                    fontSize: '16px',
                  }} />
                </div>
                <div className={styles.warningPanel}>
                  <div className={styles.warningItem}>
                    <div className={styles.warningTitle}>电池故障预警数</div>
                    <div className={styles.warningNum}>
                      <span style={{color: '#FE734D'}}>{ currentData.faultNum || 0 }</span>次
                      <RightOutlined 
                        className={styles.iconRightLine} 
                        onClick={() => {
                          this.goPageFaultWarning()
                        }}
                        style={{
                          color: '#228cff',
                          fontSize: '16px',
                        }} /> 
                    </div>
                  </div> 
                  <div className={styles.warningItem}>
                    <div className={styles.warningTitle}>高风险预警数</div>
                    <div className={styles.warningNum}>
                      <span style={{ color: '#FE734D' }}>{ currentData.levelHighNum || 0 }</span>次
                      <RightOutlined
                        className={styles.iconRightLine}
                        onClick={() => {
                          this.goPageWarningVehicle()
                        }}
                        style={{
                          color: '#228cff',
                          fontSize: '16px',
                        }} /> 
                    </div>
                  </div> 
                </div>
              </div>
              <div className={styles.view2}>
                <Row className={styles.warningPanel}>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>累计电池故障预警数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.faultNumTotal || 0 }</span>次
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>累计高风险预警数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.levelHighNumTotal || 0 }</span>次
                      </div>
                    </div>
                  </Col>
                </Row>

                {/* <div className={styles.warningPanel}></div> */}
              </div>
              <div className={styles.view3}>
                <Row className={styles.warningPanel}>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>平台接入车辆数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.totalCount || 0 }</span>辆
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>今日新接入车辆数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.newCount || 0 }</span>
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>累计预警车辆数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.warningCount || 0 }</span>辆
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>高风险预警处理中</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.levelHighHandlingNum || 0 }</span>件
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>累计高风险预警车辆数</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.highWarningCount || 0 }</span>辆
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>高风险预警处理完成</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.levelHighHandledNum || 0 }</span>件
                      </div>
                    </div>
                  </Col>
                  <Col span={24}>
                    <div className={styles.warningItem}>
                      <div className={styles.warningTitle}>数据更新时间</div>
                      <div className={styles.warningNum}>
                        <span>{ currentData.updateTime || '' }</span>
                      </div>
                    </div>
                  </Col>
                </Row>
                {/* <div className={styles.warningPanel}></div> */}
              </div>
            </div>
            <div className={styles.topViewMid}>
              <div className={styles.mapChina} id={'mapEchart'} />
            </div>
            <div className={styles.topViewRight}>
              <div className={styles.tableTile}>当前预警次数排名</div>
              <div className={styles.table}>
                <Table 
                  columns={columns}
                  dataSource={dataSource}
                  pagination={false}
                  size={"small"}
                  scroll={{ y: 420 }}
                  onRow={record => {
                    const name = this.getProvinceName(record.province)
                    return {
                      onMouseEnter: event => {
                        if (this.state.mapEchart && name) {
                          this.state.mapEchart.dispatchAction({
                            type: 'highlight',
                            geoIndex: 0,
                            geoId: 'myMap',
                            name: name,
                          });
                        }
                      },
                      onMouseLeave: event => {
                        if (this.state.mapEchart && name) {
                          this.state.mapEchart.dispatchAction({
                            type: 'downplay',
                            geoIndex: 0,
                            geoId: 'myMap',
                            name: name,
                          });
                        }
                      },
                    }
                  }}
                />
              </div>
            </div>
          </div>
          <div className={styles.midView}>
            <Row gutter={[24, 24]}>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={styles.chartHeader}>
                    累计电池故障预警类型占比
                  </div>
                  <div id="annularChart1" className={styles.chartItem}></div>
                </div>
              </Col>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={classnames(styles.chartHeader, styles.chartHeader2)}>
                    电池故障预警类型占比
                    <div className={styles.chartBtnList}>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart3DateType == 0})} onClick={() => {
                        this.changeAnnularChart3Date(0)
                      }}>昨天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart3DateType == 1})} onClick={() => {
                        this.changeAnnularChart3Date(1)
                      }}>近7天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart3DateType == 2})} onClick={() => {
                        this.changeAnnularChart3Date(2)
                      }}>近30天</div>
                    </div>
                  </div>
                  <div id="annularChart3" className={styles.chartItem}></div>
                </div>
              </Col>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={classnames(styles.chartHeader, styles.chartHeader2)}>
                    电池故障预警类型数量趋势
                    <div className={styles.chartBtnList}>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: lineChart1DateType == 1})} onClick={() => {
                        this.changeLineChart1Date(1)
                      }}>近7天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: lineChart1DateType == 2})} onClick={() => {
                        this.changeLineChart1Date(2)
                      }}>近30天</div>
                    </div>
                  </div>
                  <div id="lineChart1" className={styles.chartItem}></div>
                </div>
              </Col>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={styles.chartHeader}>
                    累计电池故障预警级别占比
                  </div>
                  <div id="annularChart2" className={styles.chartItem}></div>
                </div>
              </Col>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={classnames(styles.chartHeader, styles.chartHeader2)}>
                    电池故障预警级别占比
                    <div className={styles.chartBtnList}>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart4DateType == 0})} onClick={() => {
                        this.changeAnnularChart4Date(0)
                      }}>昨天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart4DateType == 1})} onClick={() => {
                        this.changeAnnularChart4Date(1)
                      }}>近7天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: annularChart4DateType == 2})} onClick={() => {
                        this.changeAnnularChart4Date(2)
                      }}>近30天</div>
                    </div>
                  </div>
                  <div id="annularChart4" className={styles.chartItem}></div>
                </div>
              </Col>
              <Col xs={24} sm={12} md={12} lg={12} xl={8}>
                <div className={styles.chartBox}>
                  <div className={classnames(styles.chartHeader, styles.chartHeader2)}>
                    电池故障预警级别数量趋势
                    <div className={styles.chartBtnList}>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: lineChart2DateType == 1})} onClick={() => {
                        this.changeLineChart2Date(1)
                      }}>近7天</div>
                      <div className={classnames(styles.chartBtn, {[styles.chartBtnActive]: lineChart2DateType == 2})} onClick={() => {
                        this.changeLineChart2Date(2)
                      }}>近30天</div>
                    </div>
                  </div>
                  <div id="lineChart2" className={styles.chartItem}></div>
                </div>
              </Col>
            </Row> 
          </div>
          {/* <div className={styles.midView}>
            <div className={styles.chartRow}>
              <div className={styles.chartItem}>
                <div className={styles.chartTitle}>累计电池故障预警类型占比</div>
                <div className={styles.chartBox}>
                  
                </div>
              </div>
            </div>
          </div> */}
        </Card>
      </div>
    )
  }
}
export default connect(mapStateToProps)(Overview);
